import {Cask} from 'cascadium';
import {Category} from 'cascadium-ledger';
import {Rule} from 'cascadium-formulae';

import uniformedCategories from './uniformed-categories';
import {unifyCols} from '../unify-cols';

const cols = {
  'curr.code':  {desc:'科目代码', width: 50, isFilterable: true},
  'curr.name':  {desc:'科目名称', width: 250, isFilterable: true},
  'opening.dr': {desc:'期初借方', width: 30, type:'number', isSortable: true},
  'opening.cr': {desc:'期初贷方', width: 30, type:'number', isSortable: true},
  'accrual.dr': {desc:'借方发生', width: 30, type:'number', isSortable: true},
  'accrual.cr': {desc:'贷方发生', width: 30, type:'number', isSortable: true},
  'closing.dr': {desc:'期末借方', width: 30, type:'number', isSortable: true},
  'closing.cr': {desc:'期末贷方', width: 30, type:'number', isSortable: true},
  'dest.name':  {desc:'对方科目', width: 250, isSortable: true},
  voucherID:    {desc:'凭证编号', width: 150, isSortable: true},
  desc:         {desc:'凭证信息', width: 350, isFilterable: true}
}

const importProc = (name, data, books) => {

  if (name === 'UNIFORMED_CATEGORIES') {
    const categoryReplacedData = data.filter(({upperCate, name}) => {
      return upperCate === undefined || upperCate === name
    })

    const categoryReplaceInfo = new Cask(...data)
      .grip('upperCate')
      .map(([k, v]) => [k, v.map(({name}) => name)])
      .getDict();
      
    console.log(categoryReplaceInfo);

    const categoryEntries = unifyCols(categoryReplacedData, {EntryCons:Category});

    for (let i = 0; i < categoryEntries.length; i++) {
      const {attr, curr:{name}} = categoryEntries[i];
      attr.subCate = categoryReplaceInfo[name];
    }
    
    const category = new Category({code: '', name: '*'})
      .nestFrom(categoryEntries, 'curr.code');

    return category;
  }

  if (name === 'UNIFORMED_CATEGORIES_ASSIGN_RULES') {

    const sheet = data['RULES-科目映射规则'] ?? Object.values(data)[0];
    
    const ruleBook = books.find(({name}) => name === 'UNIFORMED_CATEGORIES_ASSIGN_RULES');
    ruleBook.data = unifyCols(sheet, {EntryCons:Rule}).grip('name');

    const {data: orig} = books.find(({name}) => name === 'UNIFORMED_CATEGORIES');
    return orig;
  }
}

const exportProc = (name, books) => {

  const {data: RULES} = books.find(({name}) => name === 'UNIFORMED_CATEGORIES_ASSIGN_RULES');
  const {data: CATE} = books.find(({name}) => name === 'UNIFORMED_CATEGORIES');
  
  console.log(RULES, 'uniformed category rules');

  const exportedEntry = ({curr:{name, code}, attr:{categoryType}}) => {
    return {
      项目名称: name,
      项目编号: code,
      条目类别: categoryType,
    }
  }

  const exportedRule = ({name, positiveDest, negativeDest, allocateSubs}) => {
    return {
      科目名称: name,
      余额为正: positiveDest,
      余额为负: negativeDest,
      分配子级: allocateSubs,
    };
  }
  
  const exportedUncated = ({curr:{name}}) => {
    return {
      科目名称: name,
    };
  }

  const sheets = {
    'ENTRIES-试算平衡表项目': CATE.map(exportedEntry),
    'RULES-试算平衡表规则': Object.values(RULES).flat().map(exportedRule),
    'UNCATED-未分配科目': CATE.find(({code}) => code === '0000').succ.map(exportedUncated)
  };

  return sheets;
}

export const spec = {
  name: 'UNIFORMED_CATEGORIES',
  desc: '标准化科目',
  descAddi: 'Uniformed Categories',
  cols,
  data: importProc('UNIFORMED_CATEGORIES', uniformedCategories),
  dataTool: {
    useImport: {
      dataSpecs: [
        {
          name: 'UNIFORMED_CATEGORIES_ASSIGN_RULES',
          desc: '与科目余额表对应规则',
        },
      ],
      proc: importProc,
    },
    useExport: {
      displayName: '导出试算平衡表规则Excel',
      proc: exportProc
    }
  },
  eval: {
    next: ['UNIFORMED_CATEGORIES_ASSIGN_RULES']
  },
}
